package cn.yogehaoren.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author WangNing
 * @since 1.0
 */
public class DirectConsumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("k8s-node2");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 设置自动重连
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(3000);

        //2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 3. 通过Connection创建Channel
        Channel channel = connection.createChannel();

        // 4. 声明
        String exchangeName = "test_direct_exchange";
        String queueName = "test_direct_queue";
        String routingKey = "test.direct";
        // 声明交换机
        // 参数1: 交换机的名称
        // 参数2: 交换机的类型 direct、topic、fanout、header
        // 参数3: 是否持久化， true为持久化
        // 参数4: 当最后绑定到Exchange上的队列删除后， 自动删除该Exchange
        // 参数5: 当前Exchange是否用户RabbitMQ内部使用， 默认为False
        // 参数6:  扩展参数，用户扩展AMQP协议自制定化使用
        channel.exchangeDeclare(exchangeName, "direct", true, false, false, null);
        // 声明queue
        channel.queueDeclare(queueName, false, false, false, null);
        // 绑定 Exchange
        channel.queueBind(queueName, exchangeName, routingKey);
        channel.queueBind(queueName, exchangeName, routingKey+".ll");

        // 5. 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        // 6. 设置channel
        channel.basicConsume(queueName, true, queueingConsumer);

        // 7. 获取消息
        while (true){

            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println("消费端: "+msg);

        }

    }

}
